package andy.ham;

import java.lang.reflect.Field;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import andy.ham.DaoMaster.DevOpenHelper;

//�̳�����listView
public class LifeDiary extends ListActivity {
	// �������
	private SharedPreferences textpassword = null;
	private String password = null;
	private boolean isSet = false;
	private EditText checkpass = null;
	// ����Ƿ��һ�ν���Ӧ��
	boolean isFirstIn = false;
	// ����һ���¼�¼
	public static final int MENU_ITEM_INSERT = Menu.FIRST;
	// �༭����
	public static final int MENU_ITEM_EDIT = Menu.FIRST + 1;
	public static final int MENU_ITEM_PASSSET = Menu.FIRST + 2;
	public static final int MENU_ITEM_HELP = Menu.FIRST + 3;
	// private static final String[] PROJECTION =
	// new String[] { DiaryColumns._ID,
	// DiaryColumns.TITLE, DiaryColumns.CREATED };
	//
	// GreenDAOʹ�õı���
	private SQLiteDatabase db;

	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private NoteDao noteDao;

	private Cursor cursor;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary_list);
		// �������Ƿ��һ�ν���Ӧ��
		checkisFirsttime();

		// ��ʼ��GreenDAO
		InitDAO();

		// ��ʼ��List
		InitList();
	}

	/*
	 * ��ʼ��DAO
	 */
	private void InitDAO() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
				null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		noteDao = daoSession.getNoteDao();

	}

	/*
	 * ��ʼ��List
	 */
	private void InitList() {
		String textColumn = NoteDao.Properties.Title.columnName;
		String dateColunm = NoteDao.Properties.Date.columnName;
		String orderBy = dateColunm + " COLLATE LOCALIZED DESC";
		cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(),
				null, null, null, null, orderBy);
		String[] from = { textColumn, dateColunm };
		int[] to = { R.id.text1, R.id.created };

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.diary_row, cursor, from, to);
		setListAdapter(adapter);
	}

	private void checkisFirsttime() {
		SharedPreferences preferences = getSharedPreferences("first_pref",
				MODE_PRIVATE);
		isFirstIn = preferences.getBoolean("isFirstIn", true);
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				Intent intent = new Intent();
				if (isFirstIn) {
					// ������͸���̳̽���
					intent = new Intent(LifeDiary.this, GuideActivity.class);
					LifeDiary.this.startActivity(intent);
				} else {
					// ����������
					checkPass();
				}

			}
		}, 0);
	}

	// �������
	private void checkPass() {
		textpassword = getSharedPreferences("pass", Context.MODE_PRIVATE);
		password = textpassword.getString("password", null);
		isSet = textpassword.getBoolean("isSet", false);
		if (isSet) {
			LayoutInflater factory = LayoutInflater.from(LifeDiary.this);
			final View textEntry = factory.inflate(R.layout.confirm_pass, null);
			AlertDialog.Builder bulider = new AlertDialog.Builder(this)
					.setTitle(getString(R.string.pass_con_title))
					.setIcon(
							getResources().getDrawable(
									android.R.drawable.ic_lock_lock))
					.setView(textEntry)
					.setCancelable(false)
					.setPositiveButton(getString(R.string.ok),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									checkpass = (EditText) textEntry
											.findViewById(R.id.check_pass);
									if (checkpass.getText().toString().trim()
											.equals(password)) {
										// �رնԻ���
										try {
											Field field = dialog
													.getClass()
													.getSuperclass()
													.getDeclaredField(
															"mShowing");
											field.setAccessible(true);
											field.set(dialog, true);
										} catch (Exception e) {
											e.printStackTrace();
										}
										dialog.dismiss();
									} else {
										// �Ի�����ʧ��toast��ʾ�������
										try {
											Field field = dialog
													.getClass()
													.getSuperclass()
													.getDeclaredField(
															"mShowing");
											field.setAccessible(true);
											field.set(dialog, false);
										} catch (Exception e) {
											e.printStackTrace();
										}
										Toast.makeText(LifeDiary.this,
												R.string.password_wrong,
												Toast.LENGTH_LONG).show();
										// ���ﲻҪ���ǰ�������������Ϊ��
										checkpass.setText("");
									}
								}
							});
			bulider.create().show();
		}
	}

	// ���ѡ��˵�
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, MENU_ITEM_INSERT, 0, R.string.menu_insert);
		menu.add(Menu.NONE, MENU_ITEM_PASSSET, 0, R.string.menu_passset);
		menu.add(Menu.NONE, MENU_ITEM_HELP, 0, R.string.help_menu);
		return true;
	}

	// ���ѡ��˵���ѡ���¼�
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// ����һ������
		case MENU_ITEM_INSERT:
			Intent intent0 = new Intent(this, DiaryEditor.class);
			intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
			intent0.setData(getIntent().getData());
			startActivity(intent0);
			LifeDiary.this.finish();
			cursor.requery();
			return true;

		case MENU_ITEM_PASSSET:
			// ��������
			Intent intent = new Intent(LifeDiary.this,
					SetPasswordActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			LifeDiary.this.finish();
			break;
			
		case MENU_ITEM_HELP:
			// ��������
			Intent intent2 = new Intent(LifeDiary.this,
					Help.class);
			startActivity(intent2);
			overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			LifeDiary.this.finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		// Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
		String mid = Long.toString(id);
		Log.d("id", mid);
		// Intent intent = new Intent();
		// startActivity(new Intent(DiaryEditor.EDIT_DIARY_ACTION, uri));
		Intent intent = new Intent(this, DiaryEditor.class);
		intent.setAction(DiaryEditor.EDIT_DIARY_ACTION);
		Bundle bundle = new Bundle();
		bundle.putLong("id", id);
		intent.putExtras(bundle);
		Log.d("id", mid);
		startActivity(intent);
		LifeDiary.this.finish();
		cursor.requery();
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		cursor.requery();
		super.onActivityResult(requestCode, resultCode, intent);
		// renderListView();
	}
	// @SuppressWarnings("deprecation")
	// private void renderListView() {
	// Cursor cursor = managedQuery(getIntent().getData(), PROJECTION,
	// null,null, DiaryColumns.DEFAULT_SORT_ORDER);
	//
	// SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
	// R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
	// DiaryColumns.CREATED }, new int[] { R.id.text1,R.id.created });
	// setListAdapter(adapter);
	// }
}
